<?php

$thisPage = "companyprofile";
$subpage = getRequestParameter("subpage", false);

$extraparams = unserialize(stripslashes(getRequestParameter("params")));
$lang = getRequestParameter("lang", "hun");

TemplateHelper::useLayout("form");

loadJQueryPlugin("hsinput");
loadJQueryPlugin("multipageform");
loadJQueryPlugin("multiplier");
loadJQueryPlugin("allower");
loadJQueryPlugin("fileuploader");
loadJQueryPlugin("json-2.3");

addDataService("getlogo");
addHtmlService("getlogo");
addDataService("gethsdata");
addDataservice("gethslist");
addDataService("save");
addDataservice("getallhs");
addDataservice("geths4fromhs2");
adddataservice("geths2");
addDataService("getlogobycompany");
addDataservice("view");
addHtmlService("view");
adddataservice("renewlead");

$language = array(
    eng => array(
        title => "Company profile",
        sendorder => "Your order details will be sent to your e-mail address",
        contactinfo => "Contact Info",
        companyname => "Company name",
        uploadcompanylogo => "Upload company logo",
        freeofcharge => "Free of charge in 2012",
        changepw => "password change",
        addbanner => "add banner",
        addlogo => "add logo",
        address => "Address",
        englishws => "English website",
        hungarianws => "Hungarian website",
        exportcp => "Export contact person",
        importcp => "Import contact person",
        jobtitle => "Job title",
        contactperson => "Contact person",
        email => "Email",
        phone => "Phone",
        fax => "Fax",
        areyousure => "Are you sure that you don't want the following:",
        lst_emailupdates => "Email updates",
        longterm => "For long term advertising or multiple featured ad requests please contact <a href='mailto:info@lancasterconsulting.hu'>info@lancasterconsulting.hu</a>",
        emailupdates => "yes, email me updates, business leads, newsletters and special offers",
        savecontact => "Save contact",
        exportimportproducts => "Export import products",
        inthepast => "In the past 3 years my company carried out",
        exportactivities => "export and ",
        importactivities => "import activities",
        exportproducts => "Export products",
        productname => "Product name",
        addmore => "add mire",
        hscode => "HS code",
        zipcode => "Zipcode",
        city => "City",
        street => "Street",
        sttype => "Street type",
        houseno => "House no.", 
        sponsorhscode => "Featured position. We suggest you to sponsor HS4 code in order to be on top of the list",
        yessponsorhs4 => "Yes, I would like to sponsor HS4 code for",
        monthfor => "for",
        bannerfor => "for",
        taxno => "Tax number",
        month => "month(s)",
        payed => "PAYED",
        ordered => "ORDERED",
        waiting => "WAITING",
        addmore => "add more",
        importproducts => "Import products",
        advertisement => "Advertisement",
        placebannerad => "<b>I would like to place banner advertisement</b> (visible for 6 seconds in every 24 seconds) on the",
        hepage => "Hungarian exporters page",
        hipage => "hungarian importers page",
        blpage => "Business leads page",
        svcpage => "Servicee in Hungary",
        habroad => "Hungarian companies abroad page",
        yestou => 'Yes, I understand and agree with the <a href="index.php?choice=termsofuse" target="_blank">Terms and Conditions</a> of the Site.',
        total => "Total amount",
        totaldesc => "EUR and USD prizes are for information purposes only",
        discountcode => "Discount code",
        saveexpimp => "save",
        changebanner => "change banner",
        free1month => "free for 2 month",
        optional => "Optional",

        hungarianabroad => "Hungarian company abroad",
        ha_productname => "Selling/buying product name", 
        producths4 => "Product HS4 code (filled automatically)",
        activity => "Company activity",
        ha_bannersponsor => "I would like to",
        ha_bannerad => "place a banner ad",
        ha_sponsorcountry => "sponsor my country search page",
        country => "Country",
        savehabroad => "save",

        businesslead => "Business lead",
        buyinglead => "buying lead",
        sellinglead => "selling lead",
        bl_selecttype => "Select lead type",
        bl_listtitle => "Added leads",
        bl_productname => "Enter product name",
        bl_description => "Product description",
        bl_hs4 => "Product HS4 code",
        bl_quantity => "Quantity",
        bl_unit => "Unit",
        bl_origin => "Country of orgiin",
        bl_dest => "Country of destination",
        bl_bannersponsor => "I would like to",
        bl_bannerad => "place a banner ad",
        bl_uploadsell => "upload sell business lead logo",
        bl_uploadbuy => "upload buy business lead logo",
        bl_uploadphoto => "upload photo of the product (6000 HUF)",
        bl_addphoto => "add photo",
        bl_save => "save",
        bl_renew => "renew",
        bl_addnew => "add lead",
        units => "liters,gallons,kilograms,pieces,meters,tons,boxes",
    ),
    hun => array(
        title => "Cégprofil", 
        contactinfo => "Kapcsolati Info",
        companyname => "Cég neve",
        zipcode => "Irányítószám",
        city => "Város",
        street => "Közterület",
        sttype => "Közterület jellege",
        houseno => "Házszám", 
        sendorder => "Megrendelésének adatait e-mailben is elküldjük Önnek.",
        uploadcompanylogo => "Céglogo feltöltése",
        freeofcharge => "2012-ben ingyenes",
        taxno => "Adószám",
        addbanner => "új banner",
        addlogo => "új logo",
        address => "Cím",
        englishws => "Angol nyelvű honlap",
        hungarianws => "Magyar nyelvű honlap",
        exportcp => "Export kapcsolattartó",
        importcp => "Import kapcsolattartó",
        jobtitle => "Beosztás",
        contactperson => "Kapcsolattartó",
        email => "Email cím",
        phone => "Telefonszám",
        areyousure => "Biztosan nem kéri az alábbiakat?",
        lst_emailupdates => "Email a frissítésekről",
        fax => "Fax",
        emailupdates => "Igen, tájékoztatást kérek üzleti lehetőségekről, ajánlatokról, hírekről és frissítésekről",
        savecontact => "mentés",
        changepw => "jelszóváltás",
        exportimportproducts => "Export import termékek",
        inthepast => "Az elmúlt 3 évben cégünk ",
        exportactivities => "export és",
        importactivities => "import tevékenységet folytatott",
        exportproducts => "Export termékek",
        productname => "Termék neve",
        addmore => "hozzáadás",
        hscode => "HS kód", 
        sponsorhscode => "Kiemelés. A HS kód (VTSZ szám) szponzorálásával a találati lista tetejére kerülhet vállalata.",
        yessponsorhs4 => "Igen, szponzorálni szeretném a HS4 kódot",
        longterm => "Hosszú távú reklámszerződés ügyében, illetve ha több kategóriában szeretne kiemelést, keressen meg bennünket: <a href='mailto:info@lancasterconsulting.hu'>info@lancasterconsulting.hu</a>",
        monthfor => "forintért",
        changebanner => "változtatás",
        bannerfor => "",
        month => "hónapra",
        payed => "FIZETVE",
        ordered => "MEGRENDELVE",
        waiting => "ELBÍRÁLÁS ALATT",
        addmore => "hozzáadás",
        importproducts => "Import termékek",
        advertisement => "Hirdetések",
        placebannerad => "<b>Szeretnék banner hirdetést feladni</b> (24 másodpercenként 6 másodpercig látható) a",
        hepage => "Hungarian exporters oldal",
        hipage => "Hungarian importers oldal",
        blpage => "Business leads oldal",
        svcpage => "Services in Hungary oldal",
        habroad => "Hungarian companies abroad oldal",
        yestou => 'Igen, ismerem és elfogadom a honlap <a href="index.php?choice=termsofuse" target="_blank">szolgáltatási feltételeit</a>',
        total => "Teljes összeg",
        totaldesc => "Az EUR és USD értékek tájékoztató jellegűek",
        discountcode => "Kedvezménykód",
        saveexpimp => "mentés",

        hungarianabroad => "Külföldi magyar cég",
        ha_productname => "Vett/eladott ermék neve", 
        producths4 => "Termék HS kódja (automatikusan töltődik)",
        activity => "Cég tevékenysége",
        ha_bannersponsor => "Szeretnék",
        ha_bannerad => "banner hirdetést elhelyezni",
        ha_sponsorcountry => "saját országom keresőlapját támogatni",
        country => "Ország",
        savehabroad => "mentés",
        optional => "Opcionális",

        free1month => "2 hónapig ingyenes",
        businesslead => "Business lead",
        buyinglead => "vásárlási lead",
        sellinglead => "eladási lead",
        bl_selecttype => "Lead típusa",
        bl_productname => "Termék neve",
        bl_description => "Termék leírása",
        bl_hs4 => "Termék HS4 kód",
        bl_quantity => "Mennyiség",
        bl_unit => "Mértékegység",
        bl_origin => "Származási hely",
        bl_addnew => "új lead",
        bl_addphoto => "új fénykép",
        bl_dest => "Célhely",
        bl_bannersponsor => "Szeretnék",
        bl_bannerad => "banner hirdetést elhelyezni",
        bl_listtitle => "Felvett lehetőségek",
        bl_uploadsell => "eladási business lead logo-t feltölteni",
        bl_uploadbuy => "vásárlási business lead logo-t feltölteni",
        bl_uploadphoto => "termékfotót elhelyezni (6000 HUF)",
        bl_save => "mentés",
        bl_renew => "megújítás",
        units => "liter,gallon,kilogramm,darab,méter,tonna,doboz",
    ),
);

function buildLayout(&$smarty) {
    global $subpage;
    global $params;
    global $lang;

    if ($subpage === false) {
        if (getRequestParameter("mode") == "companyview") {
            TemplateHelper::useLayout("list", false);
            $smarty->assign("list", getCompanyByName($params['name']));
        } else {
            $smarty->assign("form", getProfileFormData($smarty));
        }
    } else if ($subpage == "success") {
        $smarty->assign("form", getCompanyProfileSuccessData($smarty));
    } else if ($subpage == "view") {
        $smarty->assign("form", getCompanyProfileView($smarty));
    }
}

function executeService($serviceName, $params, $smarty) {
    switch ($serviceName) {
        case "getlogo" : { return service_getcompanylogo($params); }
        case "getlogobycompany" : { return service_getcompanylogobycompany($params); }
        case "gethsdata" : { return service_gethsdata($params); }
        case "gethslist" : { return service_gethslist($params); }
        case "getallhs" : { return service_getallhs(); }
        case "save" : { return service_save($params); }
        case "geths2" : { return service_geths2($params); break; }
        case "geths4fromhs2" : { return service_geths4fromhs2($params); break; }
        case "view" : { return service_view($params, $smarty); }
        case "calculateamount" : { return service_calculateamount($params); break; }
        case "renewlead" : { return service_renewlead($params); break; }
    }
}

function service_renewlead($params) {
    Database::loadModel("businessleads");
    Database::getModel()->renewLeadByName(Auth::getProfileId(), $params['name']);
    return serviceSuccessful(array());           
}

function getCompanybyName($name) {
    global $smarty;
    Database::loadModel("companies");
    $result = Database::getModel()->getCompanyByName($name);
    $smarty->assign("item", $result);
    return array(
        content => $smarty->fetch("pages/companyprofile/companyview.tpl"),
    );
}

function service_view($params, $smarty) {
    $viewdata = getcompanyProfileView($params, $smarty);
    return $viewdata['content'];
}

function service_getcompanylogo($params) {
    Database::loadModel("files");
    $data = Database::getItem($params['fileid']);
    return asImage($data['type'], $data['content']);
}

function service_getcompanylogobycompany($params) {
    Database::loadModel("companies");
    $data = Database::getItem($params['company_id']);
    Database::loadModel("files");
    $data = Database::getItem($data['logo_id']);
    return asImage($data['type'], $data['content']);
}

function service_gethsdata($params) {
    Database::loadModel("hscodes");
    $result= array();
    if ($params['inputString'] != "" && !is_numeric($params['inputString'])) {
        $result = Database::getModel()->getLike($params['inputString']);
    } else if ($params['inputHS'] != "") {
        $result = Database::getModel()->getHSLike($params['inputHS']);
    } else if (is_numeric($params['inputString'])) {
        $result = Database::getModel()->getHSLike($params['inputString']);
    }
    return serviceSuccessful(array(
        items => $result
    ));
}

function service_geths4($params) {
    Database::loadModel("hscodes");
    $result = Database::getModel()->getHSLike($params['inputHS']);
    for ($i = 0; $i < count($result); $i++) {
        $result[$i]['chapter'] = $result[$i]['hscode'];
        $result[$i]['name_en'] = $result[$i]['description_en'];
        $result[$i]['name_hu'] = $result[$i]['description_hu'];
    }
    return serviceSuccessful(array(
        items => $result,
    ));
}

function service_geths2($params) {
    Database::loadModel("hs2");
    $result = Database::getAll($params['inputHS']);
    return serviceSuccessful(array(
        items => $result,
    ));
}

function service_geths4fromhs2($params) {
    Database::loadModel("hscodes");
    $result = Database::getAll($params['hs2code']);
    return serviceSuccessful(array(
        items => $result
    ));
}

function service_getallhs() {
    Database::loadModel("hscodes");
    $result = Database::getModel()->getLike();
    return serviceSuccessful(array(
        items => $result
    ));
}

function service_gethslist($params) {
    Database::loadModel("hscodes");
    $result = Database::getAll();
    return serviceSuccessful($result);
}

function service_save($params) {
    global $smarty;
    global $_CONFIG;

    $orderdata = array();
    $emailbody = "";
    $emailheader = "";
    $emailName = "profile_update";

    Database::loadModel("companies");
    $validation = Database::validate($params);
    if ($validation['overall'] == false) {
        return $validation;
    }
    $result = array();
    Database::loadModel("user");
    Database::getModel()->setProfileUpdated(Auth::getUserProperty("user_id"));
    if (isChecked($params, "emailupdates")) {
        Database::getModel()->setWantNewsletter(Auth::getUserProperty("user_id"));
        Auth::setUserProperty("wantnewsletter", 1);
    } else {
        Database::getModel()->clearWantNewsletter(Auth::getUserProperty("user_id"));
        Auth::setUserProperty("wantnewsletter", 0);
    }
    Database::loadModel("companies");
    if (Auth::userHasProfile()) {
        $params['company_id'] = Auth::getProfileId();
        $profileId = Auth::getProfileId();
        $calcAmountResult = service_calculateAmount(convertToCalculateAmountParams($params));
        $amount = $calcAmountResult['data']['amount'];
        if (isChecked($params, "accept_tac") && $params['sponsoration_changed'] == "1") {
            $spn = array();
            if (isChecked($params, "banner_export")) {
                if (Auth::getUserProperty("registertype") == "1") {
                    $spn['spn_export_rotator'] = addMonths($params['export_month']);
                }
                $spn['rotator_id'] = $params['banner_id'];
                $orderdata[] = array(name => "Rotator banner advertisment on export page", months => $params['export_month']);
            }
            if (isChecked($params, "banner_import")) {
                if (Auth::getUserProperty("registertype") == "1") {
                    $spn['spn_import_rotator'] = addMonths($params['import_month']);
                }
                $spn['rotator_id'] = $params['banner_id'];
                $orderdata[] = array(name => "Rotator banner advertisment on import page", months => $params['import_month']);
            }
            if (isChecked($params, "banner_bl")) {
                if (Auth::getUserProperty("registertype") == "1") {
                    $spn['spn_bl_rotator'] = addMonths($params['bl_month']);
                }
                $spn['rotator_id'] = $params['banner_id'];
                $orderdata[] = array(name => "Rotator banner advertisment on business leads page", months => $params['bl_month']);
            }
            if (isChecked($params, "banner_ad")) {
                if (Auth::getUserProperty("registertype") == "3" || Auth::getUserProperty("registertype") == "4") {
                    $spn['spn_bl_rotator'] = addMonths($params['banner_ad_month']);
                    $orderdata[] = array(name => "Rotator banner advertisment on business leads page", months => $params['banner_ad_month']);
                } else if (Auth::getUserProperty("registertype") == "2") {
                    $spn['spn_service_rotator'] = addMonths($params['banner_ad_month']);
                    $orderdata[] = array(name => "Rotator banner advertisment on services page", months => $params['banner_ad_month']);
                } else if (Auth::getUserProperty("registertype") == "1") {
                } else if (Auth::getuserProperty("registertype") == "5") {
                    $spn['spn_ha_rotator'] = addMonths($params['banner_ad_month']);
                    $orderdata[] = array(name => "Rotator banner advertisment on Hungarian companies abroad page", months => $params['banner_ad_month']);
                }
                $spn['rotator_id'] = $params['banner_id'];
            }
            if (isChecked($params, "logo")) {
                if (Auth::getUserProperty("registertype") == "3" || Auth::getUserProperty("registertype") == "4") {
                    $spn['spn_bl_logo'] = "9999-12-31";
                    $orderdata[] = array(name => "Business lead logo");
                } else if (Auth::getUserPrpoerty("registertype") == "1") {
                } else if (Auth::getuserProperty("registertype") == "5") {
                }
                $spn['logo_id'] = $params['logo_id'];
            }
            if (isChecked($params, "topic_sponsor")) {
                if (Auth::getUserProperty("registertype") == "2") {
                    $spn['spn_service_selection'] = addMonths($params['topic_sponsor_month']);
                    $orderdata[] = array(name => "Service topic sponsoration", months => $params['topic_sponsor_month']);
                } else if (Auth::getUserProperty("registertype") == "5") {
                    $spn['spn_ha_countrysearch'] = addMonths($params['country_sponsor_month']);
                    $orderdata[] = array(name => "Hungarian companies abroad country sponsoration", months => $params['country_sponsor_month']);
                }
                $spn['topic_sponsor_id'] = $params['topicsponsor_id'];
            }
            if (isChecked($params, "logo_minibanner")) {
                if (Auth::getUserProperty("registertype") == "2") {
                    $spn['spn_service_minibanner'] = addMonths($params['logo_minibanner_month']);
                    $orderdata[] = array(name => "Half banner", months => $params['logo_minibanner_month']);
                }
                $spn['minibanner_id'] = $params['minibanner_id'];
            }
            if (isChecked($params, "logo_ad")) {
                if (Auth::getUserProperty("registertype") == "2") {
                    $spn['spn_service_logo'] = addMonths($params['logo_ad_month']);
                    $orderdata[] = array(name => "Service logo", months => $params['logo_ad_month']);
                }
                $spn['logo_id'] = $params['logo_id'];
            }
/*
            if (isChecked($params, "photo")) {
                $spn['photo_id'] = $params['photo_id'];
                $spn['spn_bl_productphoto'] = "9999-12-31";
                $orderdata[] = array(name => "bl_productphoto");
            }
*/
            if (isChecked($params, "banner_services")) {
                $spn['spn_service_rotator'] = addMonths($params['services_month']);
                $spn['rotator_id'] = $params['banner_id'];
                $orderdata[] = array(name => "Rotator banner advertisment on services page", months => $params['services_month']);
            }
            if (isChecked($params, "banner_ha")) {
                $spn['spn_ha_rotator'] = addMonths($params['ha_month']);
                $spn['rotator_id'] = $params['banner_id'];
                $orderdata[] = array(name => "Rotator banner advertisment on Hungarian companies abroad page", months => $params['ha_month']);
            }
            foreach ($params as $key=>$value) {
                if ($key == "sponsor_export") {
                    $spn['export_hs4'] = array();
                    for ($i = 0; $i < count($value); $i++) {
                        if (isChecked($value, $i) && $params['hs4sponsor_export_month'][$i] > 0) {
                            $spn['export_hs4'][] = array(
                                hs4code => $params['hs4_export'][$i],
                                date => addMonths($params['hs4sponsor_export_month'][$i]),
                            );
                            $orderdata[] = array(name => "Export HS4 code sponsoration", hs4 => $params['hs4_export'][$i], months => $params['hs4sponsor_export_month'][$i]);
                        }
                    }
                } else if ($key == "sponsor_import") {
                    $spn['import_hs4'] = array();
                    for ($i = 0; $i < count($value); $i++) {
                        if (isChecked($value, $i) && $params['hs4sponsor_import_month'][$i] > 0) {
                            $spn['import_hs4'][] = array(
                                hs4code => $params['hs4_import'][$i],
                                date => addMonths($params['hs4sponsor_import_month'][$i]),
                            );
                            $orderdata[] = array(name => "Import HS4 code sponsoration", hs4 => $params['hs4_import'][$i], months => $params['hs4sponsor_import_month'][$i]);
                        }
                    }
                }
            }
            $spn['amount'] = $amount;
            unset($params['banner_ad']);
            unset($params['banner_id']);
            unset($params['photo_id']);
            unset($params['logo']);
            unset($params['photo']);
            unset($params['banner_ad_months']);
            $invoiceData = createInvoiceFor(Auth::getProfileId(), $amount);
            $invoiceId = $invoiceData['invoiceid'];
            $filename = $invoiceData['filename'];
//            $invoiceId = "SZAMLA-" . rand(1, 1000); // TODO: atirni szamla generalasra.
            Database::loadModel("payment");
            Database::getModel()->addCompanySponsorData(Auth::getProfileId(), $invoiceId, $spn);
            sendEmail("sendorder", Auth::getUserProperty("email"), array(
                orderdata => getOrderdataHtml($orderdata, $spn['amount']),
                title => Auth::getUserProperty("title"),
                firstname => Auth::getUserProperty("firstname"),
                lastname => Auth::getUserProperty("lastname"),
            ), array(
                "site/_temporary/$filename"
            ));
            Database::loadModel("companies");
        }
        if ($spn['rotator_id'] != "") {
            Database::getModel()->addRotatorBanner(Auth::getProfileId(), $spn['rotator_id']);
        }
        if ($params['companyname'] != "" || Auth::getUserProperty("registertype") == "5" && $params['extrabusinesslead'] != "1") {
// FOREIGN COMPANY
            if (Auth::getUserProperty("registertype") == "5") {
                $params['activity'] = str_replace(array("\r", "\n"), array(" ", " "), $params['activity']);
                $params['is_habroad'] = 1;
                $emailheader = "Abroad company profile update";
                $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her abroad company profile. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
            } else {
                $emailheader = "Company profile update";
                $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her company profile. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
            }
            Database::update($params);
            $result = serviceSuccessful(array());
            if (Auth::getUserProperty("registertype") == "5") {
                Database::getModel()->setHAbroad($profileId);
            }
        } else if (Auth::getUserProperty("registertype") == "1" && $params['extrabusinesslead'] != "1") {
// EXPORTER / IMPORTER
            $result = serviceSuccessfulWithRedirect(array(), "companyprofile", "success");           
//            Database::getModel()->removeHS4($profileId);
            $emailheader = "company profile update";
            $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her company profile. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
            $hs4data = array();
            foreach ($params as $key=>$value) {
                if ($key == "product_export") {
                    for ($i = 0; $i < count($value); $i++) {
                        if ($value[$i] != "") {
                            $hs4data[] = array(
                                hs4_id => $params['hs4_export'][$i],
                                imp_exp => 2,
                                freetype_text => $value[$i],
                            );
                        }
                    }
                } else if ($key == "product_import") {
                    for ($i = 0; $i < count($value); $i++) {
                        if ($value[$i] != "") {
                            $hs4data[] = array(
                                hs4_id => $params['hs4_import'][$i],
                                imp_exp => 1,
                                freetype_text => $value[$i]
                            );
                        }
                    }
                }
            }
            Database::getModel()->changeHS4($profileId, $hs4data);
        } else if (Auth::getUserProperty("registertype") == "2") {
// RECOMMENDED SERVICE
            $result = serviceSuccessfulWithRedirect(array(), "companyprofile", "success");           
            $emailheader = "Recommended service profile update";
            $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her service profile. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
            $objectId = Database::getModel()->updateRecommendedService($profileId, $params['service_type'], $params['service_description']);
            if (count($spn) > 0) {
                Database::loadModel("payment");
                Database::getModel()->addObjectSponsorData($profileId, $objectId, $invoiceId, $spn);
                Database::loadModel("companies");
            }
        } else if (Auth::getUserProperty("registertype") == "3" || Auth::getUserProperty("registertype") == "4" ||
                ($params['extrabusinesslead'] == "1" && Auth::getUserProperty("registertype") != "2")) {
// BUSINESS LEAD
            $emailName = "bl_profile";
            $result = serviceSuccessfulWithRedirect(array(), "companyprofile", "success");           
            Database::loadModel("businessleads");
            $blrow = array();
            $blSponsor = array();
            $emailheader = "Business lead profile update";
            $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her business lead profile. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
            for ($i = 0; $i < count($params['extra']); $i++) {
                $blrow = $params['extra'][$i];
                if ($blrow['productname'] == "") { continue; }
                $blrow['company_id'] = $profileId;
                $blrow['description'] = str_replace(array("\r", "\n"), array(" ", " "), $blrow['description']);
                $blrow['postdate'] = date("Y-m-d");
                $tmp = explode(" - ", $blrow['hs4']);
                $blrow['hs4'] = $tmp[0];
                $data = Database::getModel()->removeUndefinedFields($blrow);
                $objectId = Database::getModel()->saveUpdate($data, $profileId, $blrow['businesslead_id']);
                if ($blrow['photo_id'] > 0) {
                    $blSponsor[] = array(
                        object_id => $objectId,
                        type => "product_photo",
                    );
                }
            }
            Database::loadModel("payment");
            for ($i = 0; $i < count($blSponsor); $i++) {
                Database::getModel()->addObjectSponsorData($profileId, $blSponsor[$i]['object_id'], $invoiceId, array(
                    spn_bl_photo => "9999-12-31",
                    amount => $amount,
                ));
            }
            Database::loadModel("companies");
        }
    } else {
        $params['company_type'] = Auth::getUserProperty("registertype");
        $profileId = Database::addNew($params);
        $emailheader = "company contact update";
        $emailbody =
<<<EMAIL
<p>
A user on <a href="http://www.hungarianexporters.hu">www.hungarianexporters.hu</a> has just updated his/her company contact. Please, check
the details on the administrator site to accept/reject the changes.
</p>
EMAIL;
        Auth::setCompanyProfileId($profileId);
        Database::loadModel("user");
        Database::getModel()->setCompanyProfileId($profileId);
        Database::loadModel("companies");
        $result = serviceSuccessful(array());
    }
    $companyname = Database::getModel()->getCompanyName($profileId);
    $username = Auth::getUserProperty("username");
    $companylink = $_CONFIG['directories']['baseURL'] . "/company/" . convertCompanyName($companyname);
    $smarty->assign("companylink", $companylink);
    sendEmail($emailName, Auth::getUserProperty("email"), array(
        htmlcode_link => "<textarea cols=50 rows=10>" . $smarty->fetch("pages/companyprofile/companyprofile_link.tpl") .  "</textarea>",
        htmlcode_chart => "<textarea  cols=50 rows=10>" . $smarty->fetch("pages/companyprofile/companyprofile_chart.tpl") . "</textarea>",
    ));
    $admins = getConfigParameter("site", "administrator");
    for ($i = 0; $i < count($admins); $i++) {
        $name = $admins[$i]['name'];
        $emailtext =
<<<EMAIL
Dear $name,
$emailbody
Username: $username<br>
Company name: $companyname<br>

Hungarian Exporters admin Service
EMAIL;
        sendEmailWithContent($admins[$i]['email'], "Hungarian Exporters admin service - $emailheader", $emailtext);
    }
    return $result;
//    return serviceSuccessfulWithRedirect(array(), "companyprofile", "success");
}

function createInvoiceFor($id, $amount) {
    Log::debug("start invoice creation");
    $invoiceData = getConfigParameter("site", "invoiceData");
    $baseURL = getConfigParameter("directories", "baseURL");
    $sellerData = $invoiceData['sellerData'];
    Database::loadModel("companies");
    $clientData = Database::getModel()->getClientData($id);
    $invoice = new Invoice();
    $invoice->setElado($sellerData['name'], new Address(
        $sellerData['country'],
        $sellerData['city'],
        $sellerData['zipcode'],
        $sellerData['street'],
        $sellerData['sttype'],
        $sellerData['houseno']
    ), $sellerData['taxno']);
    $invoice->setVevo($clientData['companyname'], new Address(
        $clientData['country'],
        $clientData['city'],
        $sellerData['zipcode'],
        $clientData['street'],
        $clientData['sttype'],
        $clientData['houseno']
    ), $clientData['taxno']);
    $invoiceId = getInvoiceNumber();
    $invoice->setSzamlainfo($invoiceId, date("Y-m-d"), date("Y-m-d"), getPaymentDeadline(), $invoiceData['paymentMethod'], false);
    $invoice->addTetel("Hirdetési szolgáltatás", $amount, $invoiceData['VAT']);
    $invoice->calculateOsszesites();
    Log::debug("Inovice XML:" . $invoice);
    $sid = InvoiceAuth::startSession($invoiceData['username'], $invoiceData['password']);
    if ($clientData['eszamla_username'] == "") {
        InvoiceAdministration::setSID($sid);
        $result = InvoiceAdministration::registerCustomer($clientData['companyname'], $clientData['email'], $clientData['taxno']);
        $clientData['eszamla_username'] = $result['username'];
        Database::loadModel("user");
        Database::getModel()->setInvoiceUser(Auth::getUserProperty("user_id"), $result['username']);
    }
    InvoiceService::setSID($sid);
    InvoiceService::uploadInvoice($clientData['eszamla_username'], $invoice);
//    $payUrl = InvoiceService::pay($clientData['eszamla_username'], $invoice->getInvoiceNumber(), $invoice->getGrossPayment(), "HUF", $baseURL);
//    log::debug("Pay URL=$payUrl");
/*
    sendEmail("invoice", $clientData['email'], array(
        firstname => getUserProperty("firstname"),
        lastname => getUserproperty("lastname"),
        title => getUserProperty("title"),
        link => $payUrl,
    ));
*/
    $filename = $invoiceId . "_" . substr(md5(rand() * 100000), 10) . ".pdf";
    $content = InvoiceService::getInvoice($invoiceId);
    $invoiceFile = fopen("site/_temporary/$filename", "wb");
    fwrite($invoiceFile, $content);
    fclose($invoiceFile);

    InvoiceAuth::endSession();
    Database::loadModel("companies");
    Log::debug("Invoice created");
    return array(
        invoiceid => $invoiceId,
        filename => $filename,
    );
}

function getInvoiceNumber() {
    $invoiceData = getConfigParameter("site", "invoiceData");
    Database::loadModel("misc");
    $counter = Database::getModel()->getInvoiceNumber();
    return $invoiceData['invoicePrefix'] . "-" . $counter;
}

function getPaymentDeadline() {
    $invoiceData = getconfigParameter("site", "invoiceData");
    return date("Y-m-d", time() + $invoiceData['paymentDeadline'] * 24*60*60);
}

function convertCompanyName($name) {
    $subst = array(
        "." => "",
        " " => "+",
        "-" => "_",
    );
    return str_replace(array_keys($subst), array_values($subst), $name);
}

function getOrderDataHtml($orderdata, $amount) {
    global $smarty;
    global $thisPage;

    $smarty->assign("orders", $orderdata);
    $smarty->assign("amount", $amount);
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "orderdata"));
}

function getPageHeader() {
    return TemplateHelper::getDefaultPageHeader();
}

function getPageFooter() {
    return TemplateHelper::getDefaultPageFooter();
}

function getProfileFormData(&$smarty) {
    global $thisPage;
    global $extraparams;
    global $params;
    global $lang;
    global $language;

    Log::debug("Executing function: getProfileFormData");
    $huf_eur = wsGetCurrencyRate("HUF", "EUR");
    $huf_usd = wsGetCurrencyRate("HUF", "USD");

    $smarty->assign("lng", $language[$lang]);
    $smarty->assign("lang", $lang);
    $smarty->assign("huf_eur", $huf_eur);
    $smarty->assign("huf_usd", $huf_usd);
    if (Auth::isLoggedIn()) {
        initDatabase();
        Database::loadModel("companies");
        if (Auth::userHasProfile()&& !$extraparams['emptyProfile']) {
            $companyProfile = Database::getItem(Auth::getProfileId(), true);
            $sponsorDates = Database::getModel()->getSponsorData(Auth::getProfileId());
            Database::loadModel("payment");
            $orderedDates = Database::getAll("company_id=" . Auth::getProfileId());
            Database::loadModel("companies");
            $sponsor = array();
            if (is_array($sponsorDates)) {
                foreach ($sponsorDates as $key=>$value) {
                    if (!dateIsPast($value)) {
                        $payedField = str_replace("spn_", "payed_", $key);
                        if ($sponsorDates[$payedField] == 1) {
                            $sponsor[$key] = array(
                                status => "payed",
                            );
                        }
                    } else {
                        $sponsor[$key] = array(
                            status => "not payed",
                        );
                    }
                }
            }
            if (is_array($orderedDates)) {
                for ($i = 0; $i < count($orderedDates); $i++) {
                    if ($orderedDates[$i]['payment_subject'] == "export_rotator") {
                        $sponsor["spn_export_rotator"] = array(
                            status => "ordered",
                        );
                    } else if ($orderedDates[$i]['payment_subject'] == "import_rotator") {
                        $sponsor["spn_import_rotator"] = array(
                            status => "ordered",
                        );
                    } else if ($orderedDates[$i]['payment_subject'] == "businesslead_rotator") {
                        $sponsor["spn_bl_rotator"] = array(
                            status => "ordered",
                        );
                    } else if ($orderedDates[$i]['payment_subject'] == "service_rotator") {
                        $sponsor["spn_service_rotator"] = array(
                            status => "ordered",
                        );
                    } else if ($orderedDates[$i]['payment_subject'] == "ha_rotator") {
                        $sponsor["spn_ha_rotator"] = array(
                            status => "ordered",
                        );
                    } else if ($orderedDates[$i]['payment_subject'] == "ha_countrysearch") {
                        $sponsor['spn_ha_countrysearch'] = array(
                            status => "ordered",
                        );
                    }
                }
            }
            $smarty->assign("sponsor", $sponsor);
            if ($params['type'] == "businesslead" && Auth::getUserProperty("registertype") != "2") {
                $smarty->assign("displayBusinessLeadProfile", true);
            }
            if (Auth::getUSerProperty("registertype") == "1" && $params['type'] != "businesslead") {
                $companyHsProfile = Database::getModel()->getHS4(Auth::getProfileId());
                $hslist = array();
                for ($i = 0; $i < count($companyHsProfile); $i++) {
                    $hslist[] = $companyHsProfile[$i]['hs4_id'];
                }
                Database::loadModel("payment");
                $tmp = Database::getModel()->getHSOrders(Auth::getProfileId(), $hslist);
                $hsorders = array();
                for ($i = 0; $i < count($tmp); $i++) {
                    $hsorders[] = $tmp[$i]['hs4_id'];
                }
                Database::loadModel("companies");
                for ($i = 0; $i < count($companyHsProfile); $i++) {
                    if (in_array($companyHsProfile[$i]['hs4_id'], $hsorders)) {
                        $companyHsProfile[$i]['sponsor_status'] = "ordered";
                    }
                }
                $import_companyHsProfile = convertHS4ToTemplateData(1, $companyHsProfile);
                $export_companyHsProfile = convertHS4ToTemplateData(2, $companyHsProfile);
                $dt_import = TemplateHelper::createDynamicTableArray(3, $import_companyHsProfile);
                $dt_export = TemplateHelper::createDynamicTableArray(3, $export_companyHsProfile);
                $smarty->assign("export_months", 1);
                $smarty->assign("import_months", 1);
                $smarty->assign("bl_months", 1);
                $smarty->assign("import_dynamictable", $dt_import);
                $smarty->assign("export_dynamictable", $dt_export);
            } else if (Auth::getUserProperty("registertype") == "2") {
                $rs = Database::getModel()->getRecommendedService(Auth::getProfileId(), true);
                $smarty->assign("banner_ad_months", 1);
                $smarty->assign("topic_sponsor_months", 1);
                $smarty->assign("logo_ad_months", 1);
                $smarty->assign("serviceprofile", $rs);
            } else if (Auth::getUserProperty("registertype") == "3" || Auth::getUserProperty("registertype") == "4" ||
                       ($params['type'] == "businesslead" && Auth::getUserProperty("registertype") != "2")) {
                Database::loadModel("payment");
                $blorders = Database::getModel()->getOrdersFor(Auth::getProfileId());
                Database::loadModel("businessleads");
                if ($params['type'] == "businesslead") { $smarty->assign("extrabusinesslead", true); }
                $bl = Database::getModel()->getLeadsByCompanyId(Auth::getProfileId(), true);
                for ($i = 0; $i < count($bl); $i++) {
                    for ($ii = 0; $ii < count($blorders); $ii++) {
                        if ($blorders[$ii]['object_id'] == $bl[$i]['businesslead_id']) {
                            $bl[$i]['productphoto_sponsor_status'] = "ordered";
                        }
                    }
                    $bl[$i]['description'] = str_replace("\n", "\\n\"+\n\"", $bl[$i]['description']);
                    if (!dateIsPast($bl[$i]['spn_product_photo'])) {
                        if ($bl[$i]['payed_product_photo']) {
                            $bl[$i]['productphoto_sponsor_status'] = "payed";
                        }
                    }
                }
                $smarty->assign("banner_ad_months", 1);
                $smarty->assign("businessleads", $bl);
            } else if (Auth::getUserProperty("registertype") == "5") {
                $smarty->assign("banner_ad_months", 1);
                $smarty->assign("country_sponsor_months", 1);
            }
            $smarty->assign("companyprofile", $companyProfile);
        } else if (!Auth::userHasProfile()) {
            if (Auth::getUSerProperty("registertype") == "1") {
                $dt_import = TemplateHelper::createDynamicTableArray(3, array());
                $dt_export = TemplateHelper::createDynamicTableArray(3, array());
                $smarty->assign("export_months", 1);
                $smarty->assign("import_months", 1);
                $smarty->assign("bl_months", 1);
                $smarty->assign("import_dynamictable", $dt_import);
                $smarty->assign("export_dynamictable", $dt_export);
            }
        }
        $smarty->assign("hungarian_abroad", $extraparams['hungarianAbroad']);
        if ($extraparams['text']) {
            $smarty->assign("companyprofile", array(
                companyname => $extraparams['text']
            ));
        }
        return array(
            title => $language[$lang]['title'],
            content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "profile_content"))
        );
    } else {
        return TemplateHelper::redirectPage("login", "", array(
            redirecturl => "index.php?choice=profile&params=" . urlencode(serialize(array(
                text => htmlspecialchars($extraparams['text']),
                emptyProfile => 1,
                hungarianAbroad => $extraparams['hungarianAbroad'],
            )))
        ));
    }
}

function getCompanyProfileSuccessData(&$smarty) {
    global $thisPage;

    return array(
        title => "Company profile",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "companyprofile_success"))
    );
}

function getCompanyProfileView($params, $smarty) {
    global $thisPage;
    global $extraparams;
    global $params;

    initDatabase();
    $company = array();
    $smarty->assign("type", $params['type']);
    if ($params['type'] == "profile") {
        Database::loadModel("companies");
        $company = Database::getItem($params['id'], true);
        $companyhs = Database::getModel()->getHS4($params['id']);
        $smarty->assign("company", $company);
        $smarty->assign("companyhs", $companyhs);
    } else if ($params['type'] == "recommendation") {
        Database::loadModel("recommended_services");
        $recommendation = Database::getModel()->getPreview($params['id']);
        Database::loadModel("companies");
        $company = Database::getItem($recommendation['company_id'], true);
        $smarty->assign("company", $company);
        $smarty->assign("recommendation", $recommendation);
    } else if ($params['type'] == "businesslead") {
        $units = array(
            "Liters",
            "Gallons",
            "Kilograms",
            "Pieces",
            "Meters",
            "Tons",
            "Boxes",
        );
        Database::loadModel("businessleads");
        $businesslead = Database::getModel()->getPreview($params['id']);
        Database::loadModel("companies");
        $company = Database::getItem($businesslead['company_id'], true);
        $businesslead['unit'] = $units[$businesslead['unit']-1];
        $smarty->assign("company", $company);
        $smarty->assign("businesslead", $businesslead);
    } else if ($params['type'] == "habroad") {
        $abroad = array();
        Database::loadModel("companies");
        $company = Database::getItem($params['id'], true);
        $smarty->assign("company", $company);
    } else if ($params['type'] == "sponsor") {
        $abroad = array();
        Database::loadModel("companies");
        $company = Database::getItem($params['id'], true);
        $smarty->assign("company", $company);
        $sponsor = Database::getModel()->getPendingSponsorationFor($params['id']);
        $smarty->assign("sponsors", $sponsor);
    }
    return array(
        title => "",
        content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "companyprofile_view"))
    );
}

function convertHS4ToTemplateData($imp_exp, $hs4data) {
    $result = array();
    $ctr = 0;
    for ($i = 0; $i < count($hs4data); $i++) {
        if ($hs4data[$i]['imp_exp'] == $imp_exp) {
            $result[$ctr]['product_name'] = $hs4data[$i]['freetype_text'];
            $result[$ctr]['hs4'] = $hs4data[$i]['hs4_id'];
            $result[$ctr]['sponsor_status'] = $hs4data[$i]['sponsor_status'];
            $result[$ctr]['logo_id'] = $hs4data[$i]['logo'];
            $result[$ctr]['logo_url'] = "javascript:generateServiceUrl({service : 'getlogo', page : 'companyprofile', params : {fileid : '" . $hs4data[$i]['logo'] . "'} })";
            $ctr++;
        }
    }
    return $result;
}

function convertToCalculateAmountParams($params) {
    $prms = array();

    $prms['allowers'] = array();
    $prms['allowers']['sponsor_export'] = $params['sponsor_export'];
    $prms['allowers']['banner_export'] = $params['banner_export'];
    $prms['allowers']['banner_import'] = $params['banner_import'];
    $prms['allowers']['banner_bl'] = $params['banner_bl'];
    $prms['allowers']['banner_services'] = $params['banner_services'];
    $prms['allowers']['banner_ha'] = $params['banner_ha'];
    $prms['allowers']['topic_sponsor'] = $params['topic_sponsor'];
    $prms['allowers']['logo_ad'] = $params['logo_ad'];
    $prms['allowers']['topic_+sponsor'] = $params['topic_sponsor'];
    $prms['extras'] = array();
    $prms['extras']['discount'] = $params['discount'];
    $prms['extras']['logo_insert'] = $params['logo_insert'];
    $prms['months'] = array();
    $prms['months']['export_month'] = $params['export_month'];
    $prms['months']['import_month'] = $params['import_month'];
    $prms['months']['bl_month'] = $params['bl_month'];
    $prms['months']['services_month'] = $params['services_month'];
    $prms['months']['ha_month'] = $params['ha_month'];
    $prms['months']['hs4sponsor_import_month'] = $params['hs4sponsor_import_month'];
    $prms['months']['hs4sponsor_export_month'] = $params['hs4sponsor_export_month'];
    $prms['months']['topic_sponsor_month'] = $params['topic_sponsor_month'];
    $prms['months']['logo_ad_month'] = $params['logo_ad_month'];
    $prms['months']['country_sponsor_month'] = $params['country_sponsor_month'];
    return $prms;
}

function service_calculateAmount($params) {
    $today = getdate();
    $amount = 0;
    if (Auth::getUserProperty("registertype") == "1") {
//        print_r($params);
        if (isChecked($params, "allowers", "banner_export")) {
            $amount += 30000*intval($params['months']['export_month'], 10);
        }
        if (isChecked($params, "allowers", "banner_import")) {
            $amount += 30000*intval($params['months']['import_month'], 10);
        }
        if (isChecked($params, "allowers", "banner_bl")) {
            $amount += 30000*intval($params['months']['bl_month'], 10);
        }
        if (isChecked($params, "allowers", "banner_services")) {
            $amount += 30000*intval($params['months']['services_month'], 10);
        }
        if (isChecked($params, "allowers", "banner_ha")) {
            $amount += 30000*intval($params['months']['ha_month'], 10);
        }
        if (is_array($params['allowers']['sponsor_export'])) {
            for ($i = 0; $i < count($params['allowers']['sponsor_export']); $i++) {
                if (isCheckedByValue($params['allowers']['sponsor_export'][$i])) {
                    $amount += 6000 * (intval($params['months']['hs4sponsor_export_month'][$i], 10)-2);
                }
            }
        }
        if (is_array($params['allowers']['sponsor_import'])) {
            for ($i = 0; $i < count($params['allowers']['sponsor_import']); $i++) {
                if (isCheckedByValue($params['allowers']['sponsor_import'][$i])) {
                    $amount += 3000 * (intval($params['months']['hs4sponsor_import_month'][$i], 10)-2);
                }
            }
        }
    } else if (Auth::getUserProperty("registertype") == "2") {
        if (isChecked($params, "allowers", "banner_ad")) {
            $amount += 30000*intval($params['months']['banner_ad_month'], 10);
        }
        if (isChecked($params, "allowers", "topic_sponsor")) {
            $amount += 20000*intval($params['months']['topic_sponsor_month'], 10);
        }
        if (isChecked($params, "allowers", "logo_minibanner")) {
            $amount += 12000*intval($params['months']['logo_minibanner_month'], 10);
        }
        if (isChecked($params, "allowers", "logo_ad")) {
            if ($today['year'] == 2012 && $today['mon'] <= 9) {
                if (isChecked($params, 'extras', 'logo_insert')) {
                    $amount += 10000 * (intval($params['months']['logo_ad_month'], 10)-1);
                } else {
                    $amount += 10000 * intval($params['months']['logo_ad_month'], 10);
                }
            }
        }
    } else if (Auth::getUserProperty("registertype") == "3" || Auth::getUserProperty("registertype") == "4") {
        if (isChecked($params, "allowers", "banner_ad")) {
            $amount += 30000 * intval($params['months']['banner_ad_month'], 10);
        }
        if (isChecked($params, "allowers", "logo")) {
            if ($today['year'] == 2012) { $amount += 0; }
            else {
                $amount += 0;   // nem tudom mennyi a nem kedvezmenyes ertek
            }
        }
        if (isChecked($params, "allowers", "photo")) {
            $amount += 6000;
        }
    } else if (Auth::getUserProperty("registertype") == "5") {
        if (isChecked($params, "allowers", "banner_ad")) {
            $amount += 30000 * intval($params['months']['banner_ad_month'], 10);
        }
        if (isChecked($params, "allowers", "topic_sponsor")) {
            $amount += 20000 * intval($params['months']['country_sponsor_month'], 10);
        }
    }
    if ($params['extras']['photoCount'] > 0) {
        $amount += $params['extras']['photoCount'] * 6000;
    }
    if ($params['extras']['discount'] == generateCodeFor(100)) { $amount = 0; }
    if ($params['extras']['discount'] == generateCodeFor(50)) { $amount = $amount * 0.5; }
    if ($params['extras']['discount'] == generateCodeFor(40)) { $amount = $amount * 0.6; }
    if ($params['extras']['discount'] == generateCodeFor(30)) { $amount = $amount * 0.7; }
    if ($params['extras']['discount'] == generateCodeFor(20)) { $amount = $amount * 0.8; }
    if ($params['extras']['discount'] == generateCodeFor(10)) { $amount = $amount * 0.9; }
    return serviceSuccessful(array(
        amount => $amount,
    ));
}

?>
